﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace TeamBuy.AccessWebUI
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            txtEmail.Focus();
            //txtEmail.Attributes.Add("onkeydown", "if(event.keyCode==13){ event.returnValue = false;document.all[ctl00$ctl00$cphMain$cphDefault$btnSubmit].click();}");
            txtEmail.Attributes.Add("onkeydown", "SubmitKeyClick('ctl00_ctl00_cphMain_cphDefault_btnSubmit');"); //回车触发指定按钮的事
            txtPassword.Attributes.Add("onkeydown", "SubmitKeyClick('ctl00_ctl00_cphMain_cphDefault_btnSubmit');"); //回车触发指定按钮的事
            //txtPassword.Attributes.Add("onkeydown", "if(event.keyCode==13){ event.returnValue = false;document.all[ctl00$ctl00$cphMain$cphDefault$btnSubmit].click();;}");
            if (TeamBuySession.IsUserLoggedIn == true)
            {
                if (Request.QueryString["RURL"] == null)
                {
                    Response.Redirect("~/Default.aspx");
                }
                else
                {
                    Response.Redirect(HttpUtility.UrlDecode(Convert.ToString(Request.QueryString["RURL"])));
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int loggedInUserID;
            loggedInUserID = TeamBuySession.CreateUserSession(txtEmail.Text, txtPassword.Text, ckbAutoLogin.Checked);
            if (loggedInUserID > 0)
            {
                if (Request.QueryString["RURL"] == null)
                {
                    Response.Redirect("~/Default.aspx");
                }
                else
                {
                    Response.Redirect(HttpUtility.UrlDecode(Convert.ToString(Request.QueryString["RURL"])));
                }
            }
            else if (loggedInUserID == -1)
            {
                TeamBuy.AccessService.TeamBuyUserService userInfo = new AccessService.TeamBuyUserService();
                DataTable dtUser = userInfo.GetUserByEmailAndPwd(txtEmail.Text, txtPassword.Text);
                Response.Redirect("~/Unverified.aspx?ID=" + Common.PublicFunction.DESEncrypt(dtUser.Rows[0]["UserID"].ToString()));
            }
            else
            {
                Main_PublicSystemMessage1.Message = "Email或密码错误，请重新输入";
                Main_PublicSystemMessage1.MessageType = Common.MessageTypes.Error;
                Main_PublicSystemMessage1.MessageVisible = true;
                txtPassword.Text = "";
            }
        }
    }
}